package com.example.demo.controller;

import com.alibaba.fastjson.JSON;
import com.example.demo.DBmake.PostgreDB;
import com.example.demo.JsonObj.ChatMessObj;
import com.example.demo.JsonObj.FriListObj;
import com.example.demo.Utils.JsonUtil;
import com.example.demo.Utils.TokenUtil;
import com.example.demo.api.CommonResult;
import com.example.demo.entity.HeartbeatInfo;
import com.example.demo.entity.InitChatInfo;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;

@RestController
public class InitChatController {
    @RequestMapping(value = "/initChat",method = RequestMethod.POST)
    public CommonResult login(@RequestBody InitChatInfo initChatInfo){

        String token = initChatInfo.getToken();
        if(token==null)  return CommonResult.unauthorized("登录过期");
        if(!TokenUtil.verify(token)) return CommonResult.unauthorized("登录过期");

        int toUid = initChatInfo.getToUid();
        int myUid = initChatInfo.getMyUid();

//        System.out.println(toUid);
//        System.out.println(myUid);
        PostgreDB Target = new PostgreDB();

        String toNickname = Target.GetNickname(toUid);
        String frNickname = Target.GetNickname(myUid);
//        System.out.println(toNickname);
//        System.out.println(frNickname);
        if(toNickname==null || frNickname == null) return CommonResult.validateFailed();

        String toHeadPic = Target.GetHeadPic(toUid);
        String frHeadPic = Target.GetHeadPic(myUid);
//        System.out.println(toHeadPic);
//        System.out.println(frHeadPic);
        if(toHeadPic == null || frHeadPic == null) return CommonResult.validateFailed();

        ArrayList<ChatMessObj> chatMessObjs = Target.GetMessList(myUid,toUid,frNickname,toNickname,frHeadPic,toHeadPic);
        if(chatMessObjs==null) return CommonResult.validateFailed();
        String ChatMessJson = JSON.toJSONString(chatMessObjs);

//        System.out.println(ChatMessJson);
        token=TokenUtil.sign(myUid);
        return CommonResult.success(ChatMessJson,token);
    }
}